import React from 'react'
import { sleep } from 'antd-mobile/es/utils/sleep'


const Index = () => {
  // 构建数据
  let [page, SetPage] = React.useState(1)
  let [list, SetList] = React.useState([])
  let [hasMore, SethasMore] = React.useState(false)
  let ref = React.useRef(null)

  // 封装右侧滑动的按钮数据
  const right = [
    {
      key: 'delete',
      text: '删除住客',
      color: 'danger',
    }
  ]

  // 删除住客信息
  const GuestDelete = async (gid: number, e: any) => {
    if (e.key != 'delete') return false

    // 弹框
    var result = await React.UI.Dialog.confirm({
      content: '是否确认删除住客信息'
    })

    if (!result) return false

    // 组装数据
    var data = {
      busid: React.Business.id,
      id: gid
    }

    // 发请求
    var result = await React.HTTP.post("/guest/del", data)

    if (result.code == 0) {
      React.error(result.msg, () => { })
    } else {
      React.success(result.msg, () => {
        onRefresh() //重新刷新列表
      })
    }
  }


  // 下拉刷新
  const onRefresh = async () => {
    SetPage(1)
    SethasMore(true)
    SetList([])

    await sleep(1000)
    await request()
  }

  // 上拉加载
  const loadMore = async () => {
    await sleep(1000)
    request()
  }


  // 请求数据的方法
  const request = async () => {
    // 组装数据
    var data = {
      busid: React.Business.id,
      page: page
    }

    var result = await React.HTTP.post('/guest/index', data)

    if (result.code == 0) {
      // 没有更多数据
      SethasMore(false)
      return false
    } else {
      // 设置分页和列表合并
      SethasMore(true)
      SetPage(page + 1)
      SetList(list.concat(result.data))
    }
  }

  // 生命周期
  React.useEffect(() => {
    request()
  }, [])

  return (
    <>
      <link rel="stylesheet" type='text/css' href="/assets/css/guest.css" />
      <React.UI.PullToRefresh onRefresh={onRefresh}>
        {/* 列表结构 */}
        <React.UI.List>
          {
            list.map((item: any, key: number) => (<React.UI.SwipeAction ref={ref} key={key} rightActions={right} onAction={GuestDelete.bind(this, item.id)}>
              <React.UI.List.Item key={key} description={item.mobile} onClick={() => React.navigate(`/guest/edit?id=${item.id}`)}>
                {item.nickname}({item.gender_text})
              </React.UI.List.Item>
            </React.UI.SwipeAction>))
          }
        </React.UI.List>

        {/* 上拉加载 */}
        <React.UI.InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={0} />
      </React.UI.PullToRefresh>

      <div className='AddGuest'>
        <React.Router.Link to="/guest/add">添加住客</React.Router.Link>
      </div>
    </>
  )
}

export default Index
